var Skink; if (!Skink) Skink = {};

/***********
Skink.Debug
************/
if (!Skink.Debug) Skink.Debug = {};

Skink.Debug.enable = function() {
    Skink.Prefs.set('debug-enabled', true);
};

Skink.Debug.disable = function() {
    Skink.Prefs.set('debug-enabled', false);
};

Skink.Debug.setEnable = function(state) {
    if (state) {
        Skink.Debug.enable();
    } else {
        Skink.Debug.disable();
    }
};

Skink.Debug.dump = function(msg, type) {
    if (Skink.Prefs && Skink.Prefs.get('debug-enabled')) {
        if (!type) {
            type = 'info';
        }

        if (air.Introspector && air.Introspector.Console && air.Introspector.Console[type]) {
            air.Introspector.Console[type](msg);
        } else {
            air.trace(msg);
        }
        Skink.Debug.logToFile(msg);
    }
}

Skink.Debug.logToFile = function(msg) {
    var cr = air.File.lineEnding;
    var file = air.File.documentsDirectory;
    file = file.resolvePath("skink-debug.log");
    var stream = new air.FileStream();
    stream.open(file, air.FileMode.APPEND);
    now = new Date();
    stream.writeUTFBytes(now.toString() + ' : ' + msg + cr);
    stream.close();
}

Skink.Debug.showProps = function(obj, objName) {
    air.trace('dumping ' + objName);
    var result = "";
    for (var i in obj) {
        result += objName + "." + i + " = " + obj[i] + "\n";
    }
    air.trace(result);
}

Skink.Debug.dumpHTML = function() {
    var docsDir = air.File.documentsDirectory;
    try {
        docsDir.browseForSave("Save HTML As");
        docsDir.addEventListener(air.Event.SELECT, Skink.Debug.dumpHTMLSelectListener);
    } catch(error) {
        Skink.dump("Failed:" + error.message, 'error');
    }
};

Skink.Debug.dumpHTMLSelectListener = function(event) {
    var newFile = event.target;
    Skink.dump('got newFile ' + newFile.url);

    var html = $('html')[0].outerHTML;
    html = html.replace(/app:\/\//, '');
    html = html.replace(/onclick="Skink\.UI\.setSelectedTab\(this\)"/, '');

    Skink.dump('got html '.html);

    var stream = new air.FileStream();
    Skink.dump('made stream ');
    stream.open(newFile, air.FileMode.UPDATE);
    Skink.dump('opened stream ' + newFile.url);
    stream.writeUTFBytes(html);
    Skink.dump('write utfbytes ' + html);
    stream.close();
    Skink.dump('close stream')
}

Skink.Debug.insertDebugScripts = function() {
    air.trace("INSERT DEBUGGING SCRIPTS");
    var e = document.createElement("script");
    e.src = "assets/air/AIRIntrospector.js";
    e.type = "text/javascript";
    document.getElementsByTagName("head")[0].appendChild(e);
};